<template>
    <div v-loading="loading" style="width: 100%;">
        <SavePage :title="`${typeName}${form.highwayName}年度养护预算`">
            <template slot="buttons">
                <BaseButton :loading="btnLoading" @click="submit()">保存</BaseButton>
            </template>
            <template slot="body">
                <TitleTips title="基本信息" :required="true" />
                <el-form ref="form" :model="form" class="size-auto" :rules="rules" :inline="true" size="medium" label-width="86px">
                    <el-row :gutter="24">
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="年度" prop="year">
                                <el-input v-if="type === 'change' || !!change" v-model="form.year" disabled />
                                <el-date-picker
                                    v-else
                                    v-model="form.year"
                                    type="year"
                                    value-format="yyyy"
                                    placeholder="请选择"
                                    style="width: 100%"
                                    :picker-options="pickerOptions"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="负责人" prop="principal">
                                <el-input v-if="type === 'change' || !!change" v-model="form.principalName" disabled />
                                <el-select v-else v-model="form.principal" placeholder="请选择">
                                    <el-option
                                        v-for="item in userOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="上级批复" prop="higherPrincipal">
                                <el-input v-if="type === 'change' || !!change" v-model="form.higherPrincipalName" disabled />
                                <el-select v-else v-model="form.higherPrincipal" placeholder="请选择">
                                    <el-option
                                        v-for="item in superLevelUserOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>             
                </el-form>
                <FormItem ref="formItem" :form="form.contentList" :type="type"  :loading.sync="loading" />
            </template>
        </SavePage>
    </div>
</template>

<script>
import { BudgetingOldModel } from '@/models'
import FormItem from './components/FormItem'
import approverUser from '../../../mixins/approver-user'

export default {
    name: 'StandingBookAdd',
    components: {
        FormItem
    },
    mixins: [approverUser],
    data() {
        return {
            loading: true,
            model: new BudgetingOldModel(),
            form: {
                highwayName: '',
                year: null,
                tabulation: null,
                principal: null,
                higherPrincipal: null,
                budgetType: 1, // 预算类型 1-年度预算，2-季度预算，3-月度预算
                recordType: 1 // 记录类型 1-计划，2-变更 （默认为1）
            },
            rules: {
                year: [{ required: true, message: '请选择年度', trigger: 'change' }],
                principal: [{ required: true, message: '请选择负责人', trigger: 'change' }],
                higherPrincipal: [{ required: true, message: '请选择上级批复', trigger: 'change' }]
            },
            defalutUserId: null,
            number: null,
            type: 'add',
            typeName: '新建',
            recordType: null,
            btnLoading: false,
            change: false, // 是否是变更的
            pickerOptions: {}
        }
    },
    async created() {
        this.getQuery()
        this.getPeriodList()
        if (this.type === 'edit' || this.type === 'change') {
            await this.getEditDetail()
        }

        // 混淆approverUser里的2个方法
        this.getUserByOrg(this.defalutUserId || this.form.tabulation)
        this.getSuperLevelUser(this.defalutUserId || this.form.tabulation)
    },
    methods: {
        getPeriodList() {
            this.model.getPeriodList({ roadCode: this.form.roadCode }).then(res => {
                // 对日期年份选择做限制，如果有已经审批通过的，不允许再创建
                this.pickerOptions = {
                    disabledDate(time) {
                        if (!res || res.length === 0) {
                            return false
                        }
                        const year = time.getFullYear().toString()
                        let result = false
                        res.forEach(item => {
                            if (item.year === year) {
                                result = true
                            }
                        })
                        return result
                    }
                }
            })
        },
        getQuery() {
            this.type = this.$route.query.type
            this.number = this.$route.query.number
            
            // 新增时，需要parentNumber上级的number参数
            this.form.parentNumber = this.number
            // 编辑时需要当前number参数
            this.form.number = this.number
            if (this.type === 'edit') {
                this.typeName = '编辑'
                this.loading = true
                this.recordType = this.$route.query.recordType || null

                // 变更的编辑页需要获取下change参数
                this.change = this.$route.query.change || false
            } else if (this.type === 'add') {
                this.typeName = '新建'
                // 新增时，当前用户默认为制表人
                this.defalutUserId = this.$store.getters.avatar.id
                this.form.year = this.$route.query.year

                const road = JSON.parse(decodeURIComponent(this.$route.query.road))
                this.form = Object.assign(this.form, road)
            } else if (this.type === 'change') {
                this.typeName = '变更'
                this.loading = true
                this.recordType = this.$route.query.recordType || null
            }
        },
        // 获取编辑时需要的详情数据
        getEditDetail() {
            return this.model.getEditDetail({ number: this.number }).then(res => {
                // 如果是变更，列表数据要置空，重新填写
                if (this.type === 'change') { res.contentList = [] }
                this.form = res
            })
        },
        submit() {
            this.btnLoading = true
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const res = await this.$refs['formItem'].handleValidate()
                    console.log(res)
                    if (res) {
                        const form = JSON.parse(JSON.stringify(this.form))
                        // 如果是变更，这个是年度预算，添加budgetType为1，加上当前变更changeId，删除原id
                        if (this.type === 'change') {
                            form.budgetType = 1
                            form.changeId = form.id
                            delete form.id
                        }
                        const data = {
                            contentList: this.$refs['formItem'].list,
                            ...form
                        }
                        this.model.saveOrUpdate(data).then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.$router.go(-1)
                                }
                            })
                        }).finally(() => {
                            this.btnLoading = false
                        })
                    } else {
                        this.btnLoading = false
                    }
                } else {
                    this.btnLoading = false
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.el-form--inline.size-auto.width-100 {
    ::v-deep {
        // form的label-width：72px 根据实际label宽度修改
        .el-form-item__content {
            width: calc(100% - 100px);
        }
    }    
}
.margin-b-0 {
    margin-bottom: 0;
}
.add-box {
    width: 100%;
    height: 40px;
    line-height: 40px;
    margin-bottom: 24px;
    background: rgb(250, 250, 250);
    border: 1px solid #F5F7FA;
    border-radius: 5px;
    text-align: center;
    cursor: pointer;
    &:hover {
        background: rgb(240, 240, 240);
    }
    i {
        color: #171725;
        font-style: normal;
    }
}
</style>
